<template>
  <div id="category">
    <el-button type="danger" @click="addFirst({type:'category_first_add'})">添加一级分类</el-button>
    <div>
      <hr class="hr-e9e9e9" style="margin-left: -30px; margin-right: -30px" />
      <el-row :gutter="30">
        <el-col :span="8">
          <div class="category-wrap">
            <div
              class="category"
              v-for="firstitem in category.item"
              :key="firstitem.id"
            >
            <!-- 一级操作 -->
              <h4>
                <svg-icon iconClass="加号" class="jianhao"></svg-icon>
                {{ firstitem.category_name }}
                <div class="button-group">
                                                                            <!-- 对象直接传进data -->
                  <el-button size="mini" type="danger" @click="editCategory({data:firstitem,type:'category_first_edit'})" round>编辑</el-button>
                  <el-button size="mini" type="success" round
                    >添加子级</el-button
                  >
                  <el-button
                    size="mini"
                    round
                    @click="deleteCategoryComfirm(firstitem.id)"
                    >删除</el-button
                  >
                </div>
              </h4>
              <ul v-if="firstitem.children">
            <!-- 二级操作 -->
                <li
                  v-for="childrenitem in firstitem.children"
                  :key="childrenitem.id"
                >
                  {{ childrenitem.category_name }}
                  <div class="button-group">
                    <el-button size="mini" type="danger" round>编辑</el-button>
                    <el-button size="mini" round>删除</el-button>
                  </div>
                </li>
              </ul>
            </div>
          </div>
        </el-col>
        <el-col :span="16">
          <h4 class="menu-title">一级分类编辑</h4>
          <el-form label-width="142px" class="w410" ref="categoryForm">
            <el-form-item v-if="category_first_input">
              <label for="">一级分类名称:</label>
              <el-input
                v-model="form.categoryName"
                :disabled="category_first_disabled"
              ></el-input>
            </el-form-item>
            <el-form-item v-if="category_children_input">
              <label for="">二级分类名称:</label>
              <el-input
                v-model="form.secCategoryName"
                :disabled="category_children_disabled"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-form-item>
                <el-button
                  type="danger"
                  @click="submit"
                  :loading="submit_button_loading"
                  :disabled="submit_button_disabled"
                  >确认</el-button
                >
              </el-form-item>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script>
import { commom } from "@/api/common.js";
import { AddFirstCategory, GetCategory, DeleteCategory,EditCategory } from "@/api/news.js";
import { onMounted, reactive, ref,watchEffect } from "@vue/composition-api";
export default {
  name: "category",
  setup(props, { root, refs }) {
    const {getInfoCategory,categoryItem} = commom();
    //data
    //设定一个值判断一级还是二级编辑,或者判断编辑还是删除
    const sumit_button_type = ref('')
    //一级子集禁用
    const category_first_disabled = ref(true);
    //二级子集禁用
    const category_children_disabled = ref(true);
    // 按钮禁用
    const submit_button_disabled = ref(true);
    // 一级子集显示
    const category_first_input = ref(true);
    //二级子集显示
    const category_children_input = ref(true);
    // 存储要删除的变量id
    const deleteID = ref('')
    // 暂存一二子集的输入内容
    const form = reactive({
      categoryName: "",
      secCategoryName: "",
    });

    //上传的状态
    const submit_button_loading = ref(false);

    // 接受响应回来的分类信息
    const category = reactive({
      item: [],
      //定义一个数组,存放需要编辑的对象
      current:[]
    });

    /**
     * methods
     */
    const submit = () => {
      //根据提交类型状态去判断执行哪一个操作
      if(sumit_button_type.value === 'category_first_add'){
        addFirstCategory()
      }
      if(sumit_button_type.value === 'category_first_edit'){
        editFirstCategory()
      }
    };


    //点击一级分类之后二级不显示
    const addFirst = (params) => {
      //判断添加类型
      sumit_button_type.value = params.type
      category_first_input.value = true;
      category_children_input.value = false;
      category_first_disabled.value = false;
      submit_button_disabled.value = false;
      console.log(sumit_button_type.value)

    };
    


    //添加一级目录
    const addFirstCategory = ()=>{
      //非空判断
      if (!form.categoryName) {
        root.$message({
          message: "内容不能为空",
          type: "error",
        });
        return false;
      }
      //按钮加载状态
      submit_button_loading.value = true;
      AddFirstCategory({ categoryName: form.categoryName })
        .then((response) => {
          // console.log(response);
          let data = response.data;
          if (data.resCode === 0) {
            root.$message({
              message: data.message,
              type: "success",
            });
            //请求接口getCategory或者
            //使用push的方法可以不用再调用一次接口
            form.categoryName = "";
            form.secCategoryName = "";
            category.item.push(data.data);
            // refs.categoryForm.resetFields();
            // getCategory();
          }

          submit_button_loading.value = false;
        })
        .catch((error) => {
          submit_button_loading.value = false;
        });
    }
    //获取分类
    // const getCategory = () => {
    //   // console.log(123)
    //   GetCategory({})
    //     .then((response) => {
    //       let $data = response.data.data.data;
    //       // console.log($data);
    //       category.item = $data;
    //     })
    //     .catch((error) => {});
    // };

      //通过全局函数messge弹窗,确认是否删除
      const deleteCategoryComfirm = (category_id)=>{
        // 暂存id
        deleteID.value = category_id
        console.log(deleteID.value)
        //调用全局的messagebox函数
        //标记
        root.confirm({
            content: "确认删除当前信息,确认之后无法恢复",
            tip: "警告",
            catchFn:()=>{deleteID.value = ''},
            fn:deleteCategory,
            id:category_id,
          });
      }
      


    // 删除子集
    const deleteCategory = () => {
      DeleteCategory({ categoryId: deleteID.value })
        .then((res) => {
          //数组操作或者掉函数
          //ES6 查找数据索引api(   findindex    )
          let data = category.item.filter(item => {return item.id != deleteID.value})
            // category.item.splice(index,1)
            // console.log(data)
          category.item = data
        })
        .catch((error) => {});
    };



    /**
     * 编辑操作
     */
    const editCategory = (params)=>{
      //判断编辑类型
      sumit_button_type.value = params.type
      category_children_input.value = false
      category_first_disabled.value = false
      submit_button_disabled.value = false
      //点击编辑之后,把列的值传到一级分类名称input里
      form.categoryName = params.data.category_name
      //存储需要编辑的当前对象
      //点击之后把值赋给input框的同时,也替换了category数组的地址值
      category.current = params.data
      console.log(category.current)
    }

     const editFirstCategory = ()=>{
      //  加个需要修改数组的非空判断
        if(category.current.length == 0 ){
          root.$message({
           message:'请选择修改的分类',
           type:'warning'
         })
         return false
        }
       let requestData = {
         id:category.current.id,
         categoryName:form.categoryName
       }
       EditCategory(requestData).then(res=>{
         console.log(res)
         root.$message({
           message:res.data.message,
           type:'success'
         })
         category.current.category_name = res.data.data.data.categoryName
         //filter之后的地址赋给了data,data[0]就是刚刚过滤出来的总数组中id相同的对象放入data数组,
        //  let data = category.item.filter(item =>item.id ==  category.current.id)
        //  这里获得过滤后的对象地址值,这里直接修改值,就是修改
        //  data[0].category_name = res.data.data.data.categoryName
         //清空输入框还有category里面的数据
         form.categoryName = ''
         category.current = []

       }).catch(error =>{

       })
     }

    //监听categoryItem.item的变化,使用自定义全局的时候需要监听,vuex不用这个
    // watchEffect((value) =>{
    //   category.item = categoryItem.item;
    // })
    /**
     * 声明周期
     */
    onMounted(() => {
      // global方法
      // getInfoCategory();

      //vuex方法
      root.$store.dispatch('common/getCategoryInfo').then(res=>{
        // console.log(res)
        let $data = res.data.data.data
        category.item = $data
        console.log(category.item)
      }).catch(error=>{
        console.log(error)
      })
    });
    return {
      //data
      category,
      submit_button_loading,
      form,
      category_first_input,
      category_children_input,
      category_first_disabled,
      category_children_disabled,
      submit_button_disabled,
      deleteID,
      sumit_button_type,
      //methods
      submit,
      addFirst,
      deleteCategory,
      deleteCategoryComfirm,
      editCategory,
    };
  },
};
</script>

<style lang="scss" scoped>
.category-wrap {
  div:first-child {
    &:before {
      top: 20px;
    }
  }
  div:last-child {
    &:before {
      bottom: 21px;
    }
  }
}
.category {
  position: relative;
  line-height: 44px;
  cursor: pointer;
  &:before {
    content: "";
    top: 0px;
    bottom: 0px;
    left: 22px;
    position: absolute;
    width: 32px;
    border-left: 1px dotted #000;
  }
  h4 {
    position: relative;
    margin: 0;
    padding-left: 40px;
    svg {
      position: absolute;
      top: 13px;
      background-color: white;
      left: 15px;
      font-size: 17px;
    }
  }
  li {
    position: relative;
    padding-left: 36px;
    margin-left: 24px;
    &:before {
      content: "";
      top: 22px;
      left: 0;
      position: absolute;
      width: 32px;
      border: 1px dotted #000;
    }
  }
  li,
  h4 {
    @include webkit(transition, all 0.5s ease 0s);
    &:hover {
      background-color: #f3f3f3;
      .button-group {
        display: block;
      }
    }
  }
  .button-group {
    display: none;
    position: absolute;
    right: 11px;
    z-index: 2;
    font-size: 12px;
    top: 0px;
  }
}
div.el-form-item {
  // margin-bottom: 22px;
  position: relative;
  text-align: center !important;
  label {
    position: absolute;
    top: -2px;
    left: -120px;
    z-index: 1;
  }
}
.menu-title {
  line-height: 44px;
  padding-left: 22px;
  background-color: #f3f3f3;
  margin: 0 0 22px 0;
}
// .el-form-item{
//   >.el-form-item__label{
//   text-align: center !important;
// }
// }
.hr-e9e9e9 {
  // background-color: #e9e9e9;
  // width: calc(100% +60px);
  margin: 30px 0;
  border: none;
  border-bottom: 1px solid #e9e9e9;
}
.w410 {
  width: 410px;
}
</style>